import {resolve} from 'path';
import {visualizer} from 'rollup-plugin-visualizer';
import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
import {BASE, ENV, IS_ANALYSIS, IS_PROD, IS_SERVER} from './src/common/config.js';


// https://vitejs.dev/config/
export default defineConfig({
    base: BASE,
    define: {
        'process.env': JSON.stringify(ENV)
    },
    resolve: {
        alias: [
            {find: /^@\/(.*)$/, replacement: resolve(__dirname, './src/$1')}
        ].filter(Boolean)
    },
    build: {
        rollupOptions: {
            output: IS_PROD && !IS_SERVER && {
                experimentalMinChunkSize: 50 * 1024,
                manualChunks(id) {
                    // 最佳分包策略
                    // 拆分modules，可以使页面分块加载，分块展示
                    const [_1, moduleName] = id.match(/src\/modules\/(.+)\//i) || [];
                    if (moduleName) return moduleName;

                    // 将大的chunk尽可能拆分的更小，避免阻塞页面加载
                    if (/highlight.js\//.test(id)) {
                        if (/highlight.js\/.+\/languages/.test(id)) return 'vender-highlight-languages';
                        return 'vender-highlight-core';
                    }

                    if (/\/node_modules\/(?:\.pnpm)\/(@codemirror.*?)@/i.test(id)) {
                        return 'vender-codemirror';
                    }

                    const [_, vender] = id.match(/\/node_modules\/(?:\.pnpm)\/(@codemirror\+view|diff2html)@/i) || [];
                    if (vender) return `vender-${vender}`;
                }
            } || {}
        }
    },
    plugins: [
        react(),
        IS_ANALYSIS && !IS_SERVER && visualizer({
            filename: 'analysis/stats.html',
            open: true
        })
    ].filter(Boolean)
});
